import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SEModule } from '@delon/abc/se';
import { SettingsService, _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-account-settings-base',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormsModule, NzSpinModule, NzUploadModule, SEModule, NzButtonModule, NzInputModule, NzIconModule]
})
export class ProfileBaseComponent implements OnInit {
  protected readonly http = inject(_HttpClient);
  private readonly msg = inject(NzMessageService);
  protected readonly settings = inject(SettingsService);
  private readonly changeDetectorRef = inject(ChangeDetectorRef);
  constructor() {}
  avatar = '';
  userLoading = true;
  user: NzSafeAny;

  // #region geo

  provinces: NzSafeAny[] = [];
  cities: NzSafeAny[] = [];

  ngOnInit(): void {
    this.userLoading = false;
    this.user = this.settings.user;
    this.getUserInfo();
  }

  // #endregion

  getUserInfo() {
    this.http.get(`${Api.BaseUserApi}/current`).subscribe((res: NzSafeAny) => {
      if (res) {
        if (res.code === ResponseCode.SUCCESS) {
          this.user = res.data;
          this.changeDetectorRef.markForCheck();
          this.changeDetectorRef.detectChanges();
        } else {
          this.msg.warning(res.message);
        }
      } else {
        this.msg.error('失败，未知错误');
      }
    });
  }
  save() {
    this.http.put(`${Api.BaseUserApi}/perfect`, this.user).subscribe((res: NzSafeAny) => {
      if (res) {
        if (res.code === ResponseCode.SUCCESS) {
          this.msg.success('保存成功');
          this.getUserInfo();
        } else {
          this.msg.warning(res.message);
        }
      } else {
        this.msg.error('保存失败，未知错误');
      }
    });
  }
}
